﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;

namespace B.S.SmartStorPro.Read.API
{
    public class ExceptionFilterr : IExceptionFilter
    {
        private readonly ILogger<ExceptionFilterr> logger;

        public ExceptionFilterr(ILogger<ExceptionFilterr> logger)
        {
            this.logger = logger;
        }

        public void OnException(ExceptionContext context)
        {
            // 获取当前时间
            var currentTime = DateTime.UtcNow;

            // 获取控制器名称和方法名称
            var controllerName = context.RouteData.Values["controller"]?.ToString();
            var actionName = context.RouteData.Values["action"]?.ToString();

            // 获取参数信息
            var parameters = GetActionParameters(context);

            // 记录日志
            logger.LogError(context.Exception, "Exception occurred at {CurrentTime}, Controller: {ControllerName}, Action: {ActionName}, Parameters: {Parameters}",
                currentTime, controllerName, actionName, parameters);

            // 设置异常已处理
            context.ExceptionHandled = true;

            // 可选：返回一个统一的错误响应
            context.Result = new ObjectResult(new
            {
                Message = "An error occurred. Please try again later.",
                Time = currentTime,
                Controller = controllerName,
                Action = actionName,
                Parameters = parameters
            })
            {
                StatusCode = 500
            };
        }

        private string GetActionParameters(ExceptionContext context)
        {
            var parameters = new Dictionary<string, object>();

            if (context.ActionDescriptor is ControllerActionDescriptor descriptor)
            {
                var actionMethod = descriptor.MethodInfo;
                var actionParameters = actionMethod.GetParameters();

                foreach (var parameter in actionParameters)
                {
                    var parameterName = parameter.Name;
                    object parameterValue = null;

                    if (context.HttpContext.Request.HasFormContentType && parameter.ParameterType == typeof(IFormCollection))
                    {
                        parameterValue = context.HttpContext.Request.Form;
                    }
                    else if (context.HttpContext.Request.Query.ContainsKey(parameterName))
                    {
                        parameterValue = context.HttpContext.Request.Query[parameterName].ToString();
                    }
                    else if (context.HttpContext.Request.HasFormContentType && context.HttpContext.Request.Form.ContainsKey(parameterName))
                    {
                        parameterValue = context.HttpContext.Request.Form[parameterName].ToString();
                    }

                    if (parameterValue != null)
                    {
                        parameters[parameterName] = parameterValue;
                    }
                }
            }

            return string.Join(", ", parameters.Select(p => $"{p.Key}: {p.Value}"));
        }
    }
}
